﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using AvalonDock;
using System.Collections.ObjectModel;
using RiskMan.DataClass;
using RiskMan.Config;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Media;
using RiskMan.DataClass.Models.Plaza_II;
using RiskMan.Views.AboutFrom;
using RiskMan.Views.Dialogs;
using RiskMan.Views.Plaza_II;
using RiskMan.Views.Tables.TablesFortsFootCommonRepl;
using RiskMan.Views.Tables.TablesFortsFutInfoRepl;
using RiskMan.Views.Tables.TablesFortsFutorderBookRepl;
using RiskMan.Views.Tables.TablesFortsFuttradeRepl;
using RiskMan.Views.Tables.TablesFortsInfoRepl;
using RiskMan.Views.Tables.TablesFortsOrdlogRepl;
using RiskMan.Views.Tables.TablesFortsPartRepl;
using RiskMan.Views.Tables.TablesFortsPosRepl;
using RiskMan.Views.Tables.TablesFortsVmRepl;


namespace RiskMan
{
    public partial class MainWindow : Window
    {
        public static MainWindow StaticLevel;

        //private Register reg;

        public ObservableCollection<DocumentContent> MyDocuments { get; private set; }
        public Data _dataProvider;
        private Thread _stockClientThread;

        private History _history;
        public String path = "";
        private List<string> listWindow = new List<string>();


        public DateTime startNight = new DateTime();
        public DateTime endNight = new DateTime();


        public MainWindow()
        {
            StaticLevel = this;
            try
            {
                InitializeComponent();
                MyDocuments = new ObservableCollection<DocumentContent>();
                DataContext = this;

                _dataProvider = new Data();
                _history = new History(_dataProvider);
                _history.Load();

                #region загрузка вермени и тп

                try
                {
                    MenuItem_CheckForExit.IsChecked = Properties.Settings.Default.CanClose;
                    DateTime startD = Properties.Settings.Default.StartDay;
                    DateTime endD = Properties.Settings.Default.EndDay;

                    DateTime startN = Properties.Settings.Default.StartNight;
                    DateTime endN = Properties.Settings.Default.EndNight;

                    Properties.Settings.Default.StartDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                        DateTime.Now.Day, startD.Hour, startD.Minute, 0);
                    Properties.Settings.Default.EndDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                        DateTime.Now.Day, endD.Hour, endD.Minute, 0);

                    Properties.Settings.Default.StartNight = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                        DateTime.Now.Day, startN.Hour, startN.Minute, 0);
                    Properties.Settings.Default.EndNight = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                        DateTime.Now.Day, endN.Hour, endN.Minute, 0);

                    this.startNight = Properties.Settings.Default.StartNight;
                    this.endNight = Properties.Settings.Default.EndNight;
                }
                catch (Exception)
                {
                    new DialogOkCancel("При инициализации произоша ошибка", "Ошибка");
                }

                #endregion

            }
            catch (Exception ex)
            {
                new DialogOkCancel("При инициализации произоша ошибка: " + ex.Source, "Ошибка");
            }

        }


        public void dockManager_Loaded(object sender, RoutedEventArgs args)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //string uid = Cfg.GetID() + Cfg.GetMacAddress();
            //reg = new Register(uid);

            dockManager.Loaded += new RoutedEventHandler(dockManager_Loaded);


            listWindow = GetWindow();
            foreach (var item in listWindow)
            {
                PublishNewDocument(item);
            }
        }

        /// <summary>
        /// Проверяем наличе подключения и изменяем ярлыки
        /// </summary>
        public void Connecting(bool con)
        {
            //if (!this.Dispatcher.CheckAccess())
            //{
                this.Dispatcher.BeginInvoke(new Action (delegate()
                {
                    BtnConnect.IsEnabled = !con;
                    btnDisconnect.IsEnabled = con;
                }));
           // }

        }

        private List<string> GetWindow()
        {
            return (List<string>)XmlHistory.GetXmlData(XmlHistory.FilenameWindow);
        }

        private void CreateNewDocument(object sender, RoutedEventArgs e)
        {
            string baseDocTitle = ((MenuItem)sender).Header.ToString();
            for (int i = 0; i < dockManager.Documents.Count; i++)
            {
                if (dockManager.Documents[i].Title == baseDocTitle)
                {
                    dockManager.Documents[i].Activate();
                    return;
                }
            }
            PublishNewDocument(baseDocTitle);

        }

        private void PublishNewDocument(string baseDocTitle)
        {
            if (baseDocTitle == Cfg.MainTesting)
            {
                TestIndikators st = new TestIndikators()
                {
                    Name = "TestIndirators",
                    Title = baseDocTitle,
                    Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 })
                };
                MyDocuments.Add(st);
                st.Activate();
            }

            if (baseDocTitle == Cfg.MainRobotPlazaII)
            {
                PlazaIIView st = new PlazaIIView()
                {
                    Name = "PlazaIIView",
                    Title = baseDocTitle,
                    Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 })
                };
                MyDocuments.Add(st);
                st.Activate();
            }

            if (baseDocTitle == Cfg.Mainsetting)
            {
                MainSettings uc = new MainSettings()
                {
                    Name = "Settings",
                    Title = baseDocTitle,
                    Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 })
                };
                MyDocuments.Add(uc);
                uc.Activate();
            }

            #region Tables
            #region TablesFortsFootCommonRepl
            if (baseDocTitle == Cfg.MainCommon)
            {
                TableCommon uc = new TableCommon() { Name = "TableCommon", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsFutInfoRepl
            if (baseDocTitle == Cfg.MainDeliveryReport)
            {
                TableDeliveryReport uc = new TableDeliveryReport() { Name = "TableDeliveryReport", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainFutInstruments)
            {
                TableFutInstruments uc = new TableFutInstruments() { Name = "TableFutInstruments", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainFutRejectedOrders)
            {
                TableFutRejectedOrders uc = new TableFutRejectedOrders() { Name = "TableFutRejectedOrders", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainFutSessContents)
            {
                TableFutSessContents uc = new TableFutSessContents() { Name = "TableFutSessContents", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainFuturesParams)
            {
                TableFuturesParams uc = new TableFuturesParams() { Name = "TableFuturesParams", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainFutVcb)
            {
                TableFutVcb uc = new TableFutVcb() { Name = "TableFutVcb", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainMultilegDict)
            {
                TableMultilegDict uc = new TableMultilegDict() { Name = "TableMultilegDict", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainSeesion)
            {
                TableSeesion uc = new TableSeesion() { Name = "TableSeesion", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsFutorderBookRepl
            if (baseDocTitle == Cfg.MainInfo)
            {
                TableInfo uc = new TableInfo() { Name = "TableInfo", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainOrders)
            {
                TableOrders uc = new TableOrders() { Name = "TableOrders", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsFuttradeRepl
            if (baseDocTitle == Cfg.MainDeal)
            {
                TableDeal uc = new TableDeal() { Name = "TableDeal", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainHeratbeat)
            {
                TableHeratbeat uc = new TableHeratbeat() { Name = "TableHeratbeat", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainMultilegOrdersLog)
            {
                TableMultilegOrdersLog uc = new TableMultilegOrdersLog() { Name = "TableMultilegOrdersLog", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainMultlegDeal)
            {
                TableMultlegDeal uc = new TableMultlegDeal() { Name = "TableMultlegDeal", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainOrdersLog)
            {
                TableOrdersLog uc = new TableOrdersLog() { Name = "TableOrdersLog", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainSysEvents)
            {
                TableSysEvents uc = new TableSysEvents() { Name = "TableSysEvents", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsInfoRepl
            if (baseDocTitle == Cfg.MainBaseContractsParamsList)
            {
                TableBaseContractsParams uc = new TableBaseContractsParams() { Name = "TableBaseContractsParams", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsOrdlogRepl
            if (baseDocTitle == Cfg.MainFortsOrdlogReplMultilegOrdersLogList)
            {
                TableFortsOrdlogReplMultilegOrdersLog uc = new TableFortsOrdlogReplMultilegOrdersLog() { Name = "TableFortsOrdlogReplMultilegOrdersLog", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainFortsOrdlogReplOrdersLogList)
            {
                TableFortsOrdlogReplOrdersLog uc = new TableFortsOrdlogReplOrdersLog() { Name = "TableFortsOrdlogReplOrdersLog", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            if (baseDocTitle == Cfg.MainFortsOrdlogReplSysEventsList)
            {
                TableFortsOrdlogReplSysEvents uc = new TableFortsOrdlogReplSysEvents() { Name = "TableFortsOrdlogReplSysEvents", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsPartRepl
            if (baseDocTitle == Cfg.MainPart)
            {
                TablePart uc = new TablePart() { Name = "TablePart", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsPosRepl
            if (baseDocTitle == Cfg.MainPosition)
            {
                TablePosition uc = new TablePosition() { Name = "TablePosition", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }
            #endregion
            #region TablesFortsVmRepl
            if (baseDocTitle == Cfg.MainFutVm)
            {
                TableFutVm uc = new TableFutVm() { Name = "TableFutVm", Title = baseDocTitle, Background = new SolidColorBrush(new Color() { R = 145, G = 158, B = 167 }) };
                MyDocuments.Add(uc);
                uc.Activate();
            }

            #endregion
            #endregion
        }

        private void ClearDocumentsList(object sender, RoutedEventArgs e)
        {
            MyDocuments.Clear();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            listWindow.Clear();
            foreach (var item in MyDocuments)
            {
                listWindow.Add(item.Title);
            }
            SetWindow(listWindow);

            if (StockClient.Instance.IsWorking)
                try
                {
                    StockClient.Instance.IsWorking = false;

                    _stockClientThread.Join();
                }
                catch (Exception exc)
                {
                    int hr = Marshal.GetHRForException(exc);
                    Console.WriteLine("Исключение {0}", exc.Message);
                    if (-2147205116 == hr)
                        Console.WriteLine("Не удалось найти один из конфигурационных файлов");
                }
        }

        private void SetWindow(List<string> list)
        {
            XmlHistory.SetXmlData(XmlHistory.FilenameWindow, (Object)(list));
        }

        private void Button1_Click_1(object sender, RoutedEventArgs e)
        {
            if (this.Topmost == false)
            {
                this.Topmost = true;
                Button1.Style = (Style)this.Resources["TopMost_ButtonStyle"];
                Cfg.SetLog(
                    this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name +
                    ": Свойсвтво окна \"по верх всех\" - поставлено", MainWindow.StaticLevel.ListBox_Logs, GetType(),
                    MethodBase.GetCurrentMethod());
            }
            else
            {
                this.Topmost = false;
                Button1.Style = (Style)this.Resources["TopMostOut_ButtonStyle"];
                Cfg.SetLog(
                    this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name +
                    ": Свойсвтво окна \"по верх всех\" - снято", ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
            }
        }



        /// <summary>
        /// PLaza II
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="listener"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        //public static int ClientMessageCallback(Connection conn, Listener listener, Message msg)
        //{
        //    try
        //    {
        //        if (msg.Type == MessageType.MsgData)
        //        {
        //            Console.WriteLine(
        //                String.Format("Client received reply [id: {0}, data: {1}, user-id: {2}, name: {3}]",
        //                    ((DataMessage) msg).MsgId, ((DataMessage) msg).Data, ((DataMessage) msg).UserId,
        //                    ((DataMessage) msg).MsgName));
        //            {
        //                System.Console.WriteLine("client dump: {0}", msg);
        //            }
        //        }
        //        else if (msg.Type == MessageType.MsgP2MQTimeout)
        //        {
        //            Console.WriteLine("Client reply TIMEOUT");
        //        }
        //        else
        //        {
        //            Console.WriteLine(String.Format("Message {0}", msg.Type));
        //        }
        //        return 0;
        //    }
        //    catch (CGateException e)
        //    {
        //        return (int) e.ErrCode;
        //    }
        //}

        /// <summary>
        /// создание транзакционного соединия 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void BtnConnect_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                StockClient.Instance.Initiate();

                _stockClientThread = new Thread(new ThreadStart(StockClient.Instance.Run));
                _stockClientThread.Start();
            }
            catch (Exception exc)
            {
                int hr = Marshal.GetHRForException(exc);
                Console.WriteLine("Исключение {0}", exc.Message);
                if (-2147205116 == hr)
                    Console.WriteLine("Не удалось найти один из конфигурационных файлов");
            }
            int et = 2;
            //CGate.Open("ini=netsend.ini;key=11111111");
            //CGate.LogInfo("test .Net log.");
            //Connection conn = new Connection("p2tcp://127.0.0.1:4001;app_name=ntest_send");

            //Publisher publisher = new Publisher(conn, "p2mq://FORTS_SRV;category=FORTS_MSG;name=srvlink;timeout=5000;scheme=|FILE|forts_messages.ini|message");
            //Listener listener = new Listener(conn, "p2mqreply://;ref=srvlink");
            //listener.Handler += new Listener.MessageHandler(ClientMessageCallback);
            //if (reg.IsRun == false)
            //{
            //    if (reg.message.Length != 0)
            //        new DialogOkCancel(reg.message, "Регистрация");
            //    else
            //        new DialogOkCancel("Вы не зарегистрированы", "Регистрация");
            //    return;
            //}







        }

        #region icon to tray

        private System.Windows.Forms.NotifyIcon TrayIcon = null;
        private ContextMenu TrayMenu = null;

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            createTrayIcon();
        }


        private bool createTrayIcon()
        {
            bool result = false;

            if (TrayIcon == null)
            {
                TrayIcon = new System.Windows.Forms.NotifyIcon();
                TrayIcon.Icon = RiskMan.Properties.Resources.linechart_8075;
                TrayIcon.Text = "Робот Plaza II";

                TrayMenu = Grid_Temp.Resources["TrayMenu"] as ContextMenu;

                TrayIcon.Click += delegate(object sender, EventArgs e)
                {
                    if ((e as System.Windows.Forms.MouseEventArgs).Button == System.Windows.Forms.MouseButtons.Left)
                    {
                        ShowHideMainWindow(sender, null);
                    }
                    else
                    {
                        TrayMenu.IsOpen = true;
                        Activate();
                    }
                };
                result = true;
            }
            else
            {
                result = true;
            }

            TrayIcon.Visible = true;
            return result;
        }

        private void ShowHideMainWindow(object sender, RoutedEventArgs e)
        {
            TrayMenu.IsOpen = false; // спрячем менюшку, если она вдруг видима
            if (IsVisible)
            {
                Hide();
                (TrayMenu.Items[0] as MenuItem).Header = "Показать";
            }
            else
            {
                Show();
                (TrayMenu.Items[0] as MenuItem).Header = "Скрыть";
                WindowState = CurrentWindowState;
                Activate();
            }
        }

        private WindowState fCurrentWindowState = WindowState.Normal;

        public WindowState CurrentWindowState
        {
            get { return fCurrentWindowState; }
            set { fCurrentWindowState = value; }
        }

        protected override void OnStateChanged(EventArgs e)
        {
            base.OnStateChanged(e);
            if (this.WindowState == System.Windows.WindowState.Minimized)
            {
                //Hide( );
                (TrayMenu.Items[0] as MenuItem).Header = "Показать";
            }
            else
            {
                CurrentWindowState = WindowState;
            }
        }





        private bool fCanClose;

        public bool CanClose
        {
            get { return fCanClose; }
            set { fCanClose = value; }
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {

            base.OnClosing(e);
            if (RiskMan.Properties.Settings.Default.CanClose)
            {
                e.Cancel = true;
                CurrentWindowState = this.WindowState;
                (TrayMenu.Items[0] as MenuItem).Header = "Показать";

                Hide();
            }
            else
            {
                if ((new DialogYesNo("Вы действительно хотите выйти?", "Внимание!")).Result == MessageBoxResult.Yes)
                {
                    if ((new DialogYesNo("Сохранить данные?", "Внимание!")).Result == MessageBoxResult.Yes)
                    {
                        _history.Save();
                    }
                    TrayIcon.Visible = false;
                }
                else
                    e.Cancel = true;
            }
        }



        private void MenuExitClick(object sender, RoutedEventArgs e)
        {
            if ((new DialogYesNo("Вы действительно хотите выйти?", "Внимание!")).Result == MessageBoxResult.Yes)
            {
                if ((new DialogYesNo("Сохранить данные?", "Внимание!")).Result == MessageBoxResult.Yes)
                {
                    _history.Save();
                }
            }
            else
                return;

            TrayIcon.Visible = false;
            Environment.Exit(9);
            //  Close( );
        }

        #endregion

        private void MenuItem_SaveSettings_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _history.Save();
            }
            catch (Exception ex)
            {
                new DialogOkCancel(ex.ToString(), "MenuItem_SaveSettings_Click");
            }
        }

        private void MenuItem_CheckForExit_Click(object sender, RoutedEventArgs e)
        {
            RiskMan.Properties.Settings.Default.CanClose = MenuItem_CheckForExit.IsChecked;
            RiskMan.Properties.Settings.Default.Save();
        }

        #region Disconnect Trans2Quik

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StockClient.Instance.IsWorking = false;

                _stockClientThread.Join();
            }
            catch (Exception exc)
            {
                int hr = Marshal.GetHRForException(exc);
                Console.WriteLine("Исключение {0}", exc.Message);
                if (-2147205116 == hr)
                    Console.WriteLine("Не удалось найти один из конфигурационных файлов");
            }

            try
            {

            }
            catch (Exception ex)
            {
                Cfg.SetLog(ex.Message, MainWindow.StaticLevel.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
            }
        }

        #endregion

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// About form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }

        private void MenuItem_LogFolder_Click(object sender, RoutedEventArgs e)
        {
            String path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\PlazaII\\";
            if (Directory.Exists(path))
                Process.Start("explorer", path);
        }


        private void CreatePlazaDeal(object sender, RoutedEventArgs e)
        {
            Window1 w = new Window1();
            w.ShowDialog();
        }
    }
}